package com.lzh.others.basejava.Thread_21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Classname SimplePriorities
 * @Description 优先级练习
 * @Date 2021/9/14 11:22
 * @Created by liuzihao
 */
public class SimplePriorities implements Runnable {

    private int countDown = 5;
    private volatile double d;
    private int priority;

    public SimplePriorities(int priority) {
        this.priority = priority;
    }

    @Override
    public String toString() {
        //Thread.currentThread() 打印线程的名称，优先级，所属的线程组
        return Thread.currentThread() + ":" + countDown;
    }

    @Override
    public void run() {
        //优先级在run中开头定义，在构造器中设置没有用
        Thread.currentThread().setPriority(priority);
        while (true) {
            for (int i = 1; i < 100000; i++) {
                d += (Math.PI + Math.E) / (double) i;
                if (i % 1000 == 0) {
                    //表示当前线程声明我可以放弃使用cpu，建议具有相同优先级的其他线程可以运行。但是不能保证一定，只是一种倾向
                    Thread.yield();
                }
                System.out.println(this);
                if (--countDown == 0) {
                    return;
                }
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            executorService.execute(new SimplePriorities(Thread.MIN_PRIORITY));
        }
        executorService.execute(new SimplePriorities(Thread.MAX_PRIORITY));
        executorService.shutdown();
    }
}
